//
//  AppDelegate.m
//  Doctor1.0
//
//  Created by mk on 15/5/25.
//  Copyright (c) 2015年 cocoa-mk. All rights reserved.
//

#import "AppDelegate.h"
#import "BaiduMobStat.h"
#import "NewMainViewController.h"
#import "GuidePageViewController.h"

@interface AppDelegate ()<UIAlertViewDelegate, UITabBarControllerDelegate,UIAlertViewDelegate>

@property (nonatomic, strong)UIAlertView *forceAlert;
@property (nonatomic, strong)UIAlertView *goAlert;
@property (nonatomic, strong)NSString *change_log;



@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [self cheakUpDate];
    [self startBaiduMobStat];
    
    self.projConfig = [[ProjectConfig alloc]init];
    [self.projConfig loadData];
    [self.projConfig readFromUserDataFile];//获取登录信息
    

    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        GuidePageViewController * page = [[GuidePageViewController alloc]initWithNibName:@"GuidePageViewController" bundle:nil];
        self.nav = [[MyNavigationController alloc]initWithRootViewController:page];
        self.window.rootViewController = page;
    }else
    {
        NewMainViewController * mainView = [[NewMainViewController alloc]initWithNibName:@"NewMainViewController" bundle:nil];
        self.nav = [[MyNavigationController alloc]initWithRootViewController:mainView];
        self.window.rootViewController = self.nav;
    }

    
    self.appMBPHUB = [[MBProgressHUD alloc] initWithWindow:self.window];
    self.appMBPHUB.tag = 100;
    [self.window addSubview:self.appMBPHUB];
    self.appMBPHUB.mode = MBProgressHUDModeIndeterminate;
    self.appMBPHUB.labelText = @"加载中..";

// 唯一标识
//    NSString *identifierForVendor = [[UIDevice currentDevice].identifierForVendor UUIDString];
  
    //开机启动页时间
    [NSThread sleepForTimeInterval:2.0];
    return YES;
}

- (void)startBaiduMobStat
{
    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
    // 此处(startWithAppId之前)可以设置初始化的可选参数
    statTracker.shortAppVersion  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    statTracker.enableDebugOn = YES;
    [statTracker startWithAppId:@"4d2cca11f4"]; //AppId即为应用的appKe
}


- (void)cheakUpDate
{
    NSString *selfos = @"ios";
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString * selfos_version = [infoDictionary objectForKey:@"DTPlatformVersion"];
    // app build版本
    self.selfapp_Version = [infoDictionary objectForKey:@"CFBundleVersion"];
    //设备号
    NSString *selfDevice =  [DeviceManager getPlatformString];
    
    
    NSString *Url = [NSString stringWithFormat:@"/appversion?os=%@&os_version=%@&device=%@&app_version=%@&app_name=md", selfos, selfos_version, selfDevice, self.selfapp_Version];
    
    [[HttpClient manager]GET:Url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        DLog(@"=appversion:==%@",responseObject);
        id dict = [responseObject objectForKey:@"appversion"];
        if ([dict isKindOfClass:[NSDictionary class]])
        {
            if([dict objectForKey:@"errors"])
            {
                return ;
            }
            
            NSString *force_update = [dict objectForKey:@"force_update"];
            NSString *curVersion = [dict objectForKey:@"cur_app_version"];
            
            if([NSNull null] != [dict objectForKey:@"change_log"])
            {
                self.change_log = [dict objectForKey:@"change_log"];
            }
            NSInteger app_Version = [self.selfapp_Version integerValue];
            NSInteger cur_Version = [curVersion integerValue];
            if (cur_Version > app_Version)
            {
                if ([force_update integerValue]  == 1)
                {
                    self.forceAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:self.change_log delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil, nil];
                    [self.forceAlert show];
                    
                }else{
                    self.goAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:self.change_log delegate:self cancelButtonTitle:@"下次再说" otherButtonTitles:@"更新", nil];
                    [self.goAlert show];
                }
            }
      }
  
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
        
    }];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == self.forceAlert  && buttonIndex == 0) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/ming-yi-zhu-dao/id%@?mt=8&uo=4",myAppKey]]
         ];
    }
    else if (alertView == self.goAlert && buttonIndex == 1){
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/ming-yi-zhu-dao/id%@?mt=8&uo=4",myAppKey]]
         ];
    }
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
